package com.sen.config.security;

import com.sen.dto.ResourceDTO;
import com.sen.entity.Resource;
import com.sen.entity.Role;
import com.sen.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求的url分析请求所需的角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private ResourceService resourceService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation invocation = (FilterInvocation) o;
        //获取请求的url
        String requestUrl = invocation.getRequestUrl();
        List<ResourceDTO> resourceDTOS = resourceService.getResourcesWithRoles();
        for (ResourceDTO resourceDTO : resourceDTOS){
            //判断请求url与菜单角色是否匹配
            if (antPathMatcher.match(resourceDTO.getUrl(), requestUrl)){
                String[] str = resourceDTO.getRoles().stream().map(Role::getRoleName).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        //没匹配的url默认登录即可访问
        return SecurityConfig.createList("LOGIN_ROLE");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
